﻿package 
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;	
	import flash.events.Event;
	import flash.text.TextField;
	import flash.geom.ColorTransform;
	import flash.geom.Matrix;	
	import flash.geom.Point;	
	import flash.filters.BlurFilter;
	
	import org.papervision3d.materials.special.Letter3DMaterial;
	import org.papervision3d.materials.special.ParticleMaterial;
	import org.papervision3d.objects.primitives.Sphere;
	import org.papervision3d.objects.special.ParticleField;
	import org.papervision3d.render.BasicRenderEngine;
	import org.papervision3d.scenes.Scene3D;
	import org.papervision3d.view.Viewport3D;
	import org.papervision3d.cameras.Camera3D;
	import org.papervision3d.lights.PointLight3D;
	import org.papervision3d.typography.Font3D;
	import org.papervision3d.typography.fonts.HelveticaMedium;
	import org.papervision3d.typography.Text3D;	
	
	/*
	 * coded by moka 2009 / 06/ 18 
	 * name : moka's point clound
	 */

	public class Main extends Sprite 
	{		
		private var render:BasicRenderEngine;
		private var scene:Scene3D
		private var camera:Camera3D
		private var viewport:Viewport3D 
		private var bmp:Bitmap;
		private var bmpBuffer:BitmapData;
		private var pointClound:ParticleField;
		
		public function Main():void 
		{
			stage.scaleMode = "noScale"; // 設定場景不變形
			
			scene = new Scene3D(); // Scene3D 用來組織場景母子關係樹狀架構
			camera = new Camera3D(); // Camera3D 為 3D 場景可視範圍設定			
			viewport = new Viewport3D(640, 480); // Viewport3D 用在呈現於 flash 場景(其類別繼承Sprite)
			render = new BasicRenderEngine(); // 渲染 3D 場景之類別			

			pointClound = scene.addChild(new ParticleField(new ParticleMaterial(0x6666FF, 1, 1), 200, 10)) as ParticleField; // 建立粒子雲
			
			var txtMaterial:Letter3DMaterial = new Letter3DMaterial(0x3f0); //建立文字材質
			txtMaterial.oneSide = false; //雙面材質
			
			pointClound.addChild(scene.addChild(new Text3D("Moka's Point Cloud", new HelveticaMedium, txtMaterial))); // 建立文字於 pointClound 子集中
			
			bmp = addChild(new Bitmap(new BitmapData(640,480,true,0xFF000000))) as Bitmap; // viewport 改用 Bitmap 繪製
			
			addEventListener(Event.ENTER_FRAME, onProcess);	
			(addChild(new TextField()) as TextField).htmlText = "<font color='#FFFFFF'>Moka's work 2009</font>"; // Moka's work 2009
		}		
		
		public function onProcess(e:Event):void {
			render.renderScene(scene, camera, viewport); // 渲染 3D 場景	
			bmpBuffer = bmp.bitmapData.clone(); // 複製前一張場景圖		
			bmp.bitmapData.draw(bmpBuffer, new Matrix(), new ColorTransform(0, 0, 0, 0.05)); // 繪製5%透明度bmpBuffer
			bmp.bitmapData.draw(viewport); // 繪製 viewport 於 Bitmap
			bmp.bitmapData.applyFilter(bmp.bitmapData, bmp.bitmapData.rect, new Point(), new BlurFilter(2,2));// 套用模糊效果
			pointClound.rotationX = mouseX; // 旋轉粒子雲 X 軸
			pointClound.rotationY = mouseY; // 旋轉粒子雲 Y 軸				
		}
	}	
}